package Server.Game;

import java.util.ArrayList;
import java.util.Iterator;

import Server.Sessions.ClientSession;
import Server.Sessions.OutboundMessages;

import shared.Messages.BeginMessage;
import shared.Player.Player;
import shared.Tiles.Backwards2Tile;
import shared.Tiles.Backwards3Tile;
import shared.Tiles.Forward2Tile;
import shared.Tiles.Forward3Tile;
import shared.Tiles.QuestionTile;
import shared.Tiles.RegularTile;
import shared.Tiles.Tile;


public class GameStart extends Thread {
	ArrayList<ClientSession> GameClientsToGame = new ArrayList<ClientSession>();
	ArrayList<Tile> tiles = new ArrayList<Tile>();
	OutboundMessages outQueue;
	int GameNo = 0;
	int count = 0;
	String msg;
	Player p0;
	Player p1;
	Player p2;

	
	public GameStart(ArrayList<ClientSession> GameClients, OutboundMessages outQueue, 
			int GameNo){
		GameClientsToGame.addAll(GameClients);
		this.outQueue = outQueue;
		this.GameNo = GameNo;
		start();
	
		}
	
	public void run(){
		getNewGameTiles();
		Iterator<ClientSession> itr = GameClientsToGame.iterator();
		while(itr.hasNext()){
			ClientSession cli = (ClientSession) itr.next();
			switch(count){
			case 0: 
				p0 = cli.p = new Player(cli.getName(), 0, GameNo, 1, tiles.get(0));
				break;
			case 1: 
				p1 = cli.p = new Player(cli.getName(), 0, GameNo, 2, tiles.get(0));
				break;
			case 2: 
				p2 = cli.p = new Player(cli.getName(), 0, GameNo, 3, tiles.get(0));
				break;
			}
			count++;
			if(count == 3){
				outQueue.addMessage(new BeginMessage(GameNo, p0.name, p1.name, p2.name, p0.tileId, p1.tileId, p2.tileId, p0.playerID, p1.playerID, p2.playerID));
				break;
			}
		}
		while(true){
			try{
				Thread.sleep(100);
			}catch (InterruptedException e){
				System.out.println("Sleep katkestatud!");
				break;
			}
			if(playersReady()){
				new GameOK(outQueue, GameNo, p0, p1, p2, tiles);
				break;
			}
		}
	}

	private boolean playersReady() {
		Iterator<ClientSession> itr = GameClientsToGame.iterator();
		while(itr.hasNext()){
			ClientSession cli = (ClientSession) itr.next();
			if(cli.IsReady == false){
				return false;
			}
		}
		return true;
	}
	
	public void getNewGameTiles(){
		tiles.add(new RegularTile(0));
		tiles.add(new RegularTile(1));
		tiles.add(new RegularTile(2));
		tiles.add(new RegularTile(3));
		tiles.add(new Forward2Tile(4));
		tiles.add(new QuestionTile(5));
		tiles.add(new RegularTile(6));
		tiles.add(new Backwards2Tile(7));
		tiles.add(new RegularTile(8));
		tiles.add(new RegularTile(9));
		tiles.add(new QuestionTile(10));
		tiles.add(new Forward3Tile(11));
		tiles.add(new RegularTile(12));
		tiles.add(new RegularTile(13));
		tiles.add(new QuestionTile(14));
		tiles.add(new RegularTile(15));
		tiles.add(new Backwards3Tile(16));
		tiles.add(new RegularTile(17));
		tiles.add(new QuestionTile(18));
		tiles.add(new RegularTile(19));
		
	}
	}
